package storage

import (
	"context"
	"fmt"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"os"
)

func NewTencent(bucketURL, secretID, secretKey string) (*Tencent, error) {
	u, _ := url.Parse(bucketURL)
	b := &cos.BaseURL{BucketURL: u}
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  secretID,
			SecretKey: secretKey,
		},
	})
	return &Tencent{client: client}, nil
}

type Tencent struct {
	client *cos.Client
}

func (r *Tencent) Upload(filePath string, destination string) error {
	f, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("failed to open file: %v", err)
	}
	defer f.Close()

	_, err = r.client.Object.Put(context.Background(), destination, f, nil)
	if err != nil {
		return fmt.Errorf("failed to upload file: %v", err)
	}
	return nil
}
func (r *Tencent) Delete(objectName string) error {
	_, err := r.client.Object.Delete(context.Background(), objectName)
	if err != nil {
		return fmt.Errorf("failed to delete object: %v", err)
	}
	return nil
}
func (r *Tencent) Move(source string, destination string) error {
	if err := r.Copy(source, destination); err != nil {
		return err
	}
	return r.Delete(source)
}
func (r *Tencent) Copy(source string, destination string) error {
	sourceURL := fmt.Sprintf("%s/%s", r.client.BaseURL.BucketURL.String(), source)
	_, _, err := r.client.Object.Copy(context.Background(), destination, sourceURL, nil)
	if err != nil {
		return fmt.Errorf("failed to copy object: %v", err)
	}
	return nil
}
